package com.wh.usercenter3.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.usercenter3.config.RedisConfig;
import com.wh.usercenter3.constant.CodeConstant;
import com.wh.usercenter3.constant.UserConstant;
import com.wh.usercenter3.exception.BaseException;
import com.wh.usercenter3.pojo.User;
import com.wh.usercenter3.pojo.dto.UserLoginDto;
import com.wh.usercenter3.pojo.dto.UserRegisterDto;
import com.wh.usercenter3.pojo.vo.NewTeamVo;
import com.wh.usercenter3.pojo.vo.NewUserVo;
import com.wh.usercenter3.response.Result;
import com.wh.usercenter3.response.ResultUtil;
import com.wh.usercenter3.service.UserService;
import com.wh.usercenter3.util.UserUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@Tag(name = "用户模块")
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Operation(summary = "用户信息接口")
    @GetMapping("/state")
    public Result<NewUserVo> userState(HttpServletRequest request) {
        User user= (User) request.getSession().getAttribute(UserConstant.LOGIN_USER);
        NewUserVo newUserVo = new NewUserVo();
        BeanUtils.copyProperties(user,newUserVo);
        return ResultUtil.ok(newUserVo) ;
    }

    @Operation(summary = "用户登录接口")
    @PostMapping ("/login")
    public Result<NewUserVo> userLogin(@RequestBody UserLoginDto dto,HttpServletRequest request) {
        log.info("\n调用用户登录接口: "+dto);


        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", dto.getUserAccount());
        User user = userService.getOne(queryWrapper);

        request.getSession().setAttribute(UserConstant.LOGIN_USER,user);

        NewUserVo newUserVo = new NewUserVo();
        BeanUtils.copyProperties(user,newUserVo);

        return ResultUtil.ok(newUserVo);
    }

    @Operation(summary = "用户注册接口")
    @PostMapping("/register")
    public Result<NewUserVo> userRegister(@RequestBody UserRegisterDto dto,HttpServletRequest request) {
        log.info("\n调用用户注册接口: "+dto);

        User user = new User();
        BeanUtils.copyProperties(dto,user);

        userService.save(user);

        request.getSession().setAttribute(UserConstant.LOGIN_USER, user);

        NewUserVo newUserVo = new NewUserVo();
        BeanUtils.copyProperties(user,newUserVo);

        return ResultUtil.ok(newUserVo);
    }

    @Operation(summary = "用户根据id查询接口")
    @GetMapping("/query")
    public Result<NewUserVo> userQuery(@RequestParam(required = false) Long id) {
        log.info("\n调用用户查询接口: "+id);

        User user = userService.getById(id);

        NewUserVo newUserVo = new NewUserVo();
        BeanUtils.copyProperties(user,newUserVo);

        return ResultUtil.ok(newUserVo);

    }

    @Operation(summary = "用户分页查询查询接口")
    @GetMapping("/pageQuery")
    public Result<List<NewUserVo>> userPageQuery(long num, long size, HttpServletRequest request) {
        log.info("\n调用用户分页查询查询接口: {},{}",num,size);

        /*
          从用户态取当前用户信息
         */
        User nowUser = UserUtil.userByLogin(request);

        /*
           自定义redisKey
         */
        String redisKey = String.format("userCenter3;UserController;userPageQuery;%s;%s", nowUser.getId(),num);

        /*
          查看redis是否有缓存,有缓存直接返回
         */
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<NewUserVo> newUserVos = (List<NewUserVo>) valueOperations.get(redisKey);
        if (newUserVos != null) {
            return ResultUtil.ok(newUserVos);
        }

        /*
            查数据库
         */
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Page<User> userPage = userService.page(new Page<>(num, size), queryWrapper);
        List<User> userList = userPage.getRecords();

        /*
            数据脱敏
         */
        newUserVos = userList.stream()
                .map(user -> {
                    NewUserVo newUserVo = new NewUserVo();
                    BeanUtils.copyProperties(user, newUserVo);
                    return newUserVo;
                })
                .collect(Collectors.toList());

        /*
            存缓存
         */
        try {
            valueOperations.set(redisKey,newUserVos,10000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            throw new BaseException(CodeConstant.SERVICE_ERR,"无法存入redis缓存");
        }

        return ResultUtil.ok(newUserVos);

    }

    @Operation(summary = "用户删除接口")
    @DeleteMapping
    public Result userDelete(@RequestBody List<Long> ids,HttpServletRequest request) {

        log.info("\n调用用户查询接口: "+ids);

        User user = UserUtil.userByLogin(request);

        if (user.getUserRole() != 1) {
            throw new BaseException(CodeConstant.CLIENT_ERR, "无管理员权限");
        }

        userService.removeByIds(ids);

        return ResultUtil.ok();
    }

    @Operation(summary = "用户根据标签查询接口")
    @GetMapping("/query/tag")
    public Result<List<NewUserVo>> userQueryByTag(@RequestParam(required = false) List<String> tagList) {
        log.info("\n调用用户根据标签查询接口: "+tagList);
        return ResultUtil.ok(userService.userByTags(tagList));

    }

    @Operation(summary = "用户id查询队伍")
    @GetMapping("/query/team")
    public Result<NewTeamVo> teamByUserId(long userId) {
        if (userId == 0) {
            throw new BaseException(CodeConstant.CLIENT_ERR, "用户id不能为0");
        }
        NewTeamVo newTeamVo=userService.teamByUserId(userId);
        return ResultUtil.ok(newTeamVo);
    }

    @Operation(summary = "推荐用户")
    @GetMapping("/recommend")
    public Result<List<Long>> recommendUser(HttpServletRequest request) {
        // 取出当前登录用户
        User loginUser = UserUtil.userByLogin(request);
        log.info("推荐用户锚点用户为：{}",loginUser);
        // 调用server层
        List<Long> userList=userService.recommendUser(loginUser);
        if (userList.isEmpty()) {
            throw new BaseException(CodeConstant.SERVICE_ERR, "服务器错误");
        }
        return ResultUtil.ok(userList);
    }
}
